#ifndef YHAIDA_CHANNEL_H
#define YHAIDA_CHANNEL_H
#include "../base/Utils.h"
#include "../logging/Logging.h"
#include "../datetime/Timestamp.h"
#include <functional>
namespace yhaida
{
    class EventLoop;
    class Channel : Utils::nocapyable
    {
    public:
        typedef std::function<void()> EventCallBackFunc;
        typedef std::function<void(Timestamp)> ReadEventCallBackFunc;

    public:
        Channel(EventLoop *loop, int fd);
        ~Channel();
        //处理fd对应的各种回调函数
        void handleEvent(Timestamp receiveTime);

        //设置回调函数；
        void setReadCallBackFuc(const ReadEventCallBackFunc &func) { _readCallBackFunc = func; }
        void setWriteCallBackFuc(const EventCallBackFunc &func) { _writeCallBackFunc = func; }
        void setErrorCallBackFuc(const EventCallBackFunc &func) { _errorCallBackFunc = func; }
        void setCloseCallBackFuc(const EventCallBackFunc &func) { _closeCallBackFunc = func; }

        int fd() const { return _fd; }
        int events() const { return _events; }
        void setRevents(int revent) { _revents = revent; }
        int index() { return _index; }
        void set_index(int v) { _index = v; }

        bool isNoneEvent() { return _events == kNoneEvent; }

        void enableReading()
        {
            _events |= kReadEvent;
            update();
        }
        void enableWriting()
        {
            _events |= kWriteEvent;
            update();
        }
        void disableReading()
        {
            _events &= ~kReadEvent;
            update();
        }
        void disenableWriting()
        {
            _events &= ~kWriteEvent;
            update();
        }
        void disenableAll()
        {
            _events = kNoneEvent;
            update();
        }
        bool isReading() const { return _events & kReadEvent; }

        bool isWriting() const { return _events & kWriteEvent; }

        EventLoop *getMainEventLoop() { return _mainEventLoop; }

    private:
        void update();

        //共享的标志
        static const int kNoneEvent;
        static const int kReadEvent;
        static const int kWriteEvent;

        EventLoop *_mainEventLoop;
        /*
        struct pollfd {
            int fd;         		// 用于检测的文件描述符
            short events;         // 等待的事件类型
            short revents;        // 实际发生的事件类型
        } ;
        */
        const int _fd;
        int _events;
        int _revents;
        // index是该channel在_pollfds里面的第几个。
        int _index;
        // 回调函数
        ReadEventCallBackFunc _readCallBackFunc;
        EventCallBackFunc _writeCallBackFunc;
        EventCallBackFunc _errorCallBackFunc;
        EventCallBackFunc _closeCallBackFunc;

        bool _isEventHandle;
    };

}

#endif